package org.example.study.sc.service;
import lombok.extern.slf4j.Slf4j;
import org.example.redis.lock.LockType;
import org.example.redis.lock.RedisLockClient;
import org.example.study.sc.constant.SecKillConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @program: rabbitmq-study
 * @description:
 * @Version V1.0.0
 * @author: dazhi
 * @create: 2021-02-03 09:52
 **/
@Service
@Slf4j
public class SecKillService {


    //记录实际卖出的商品数量
    private AtomicInteger successNum = new AtomicInteger(0);


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private OrderMasterService orderMasterService;

    @Autowired
    RedisLockClient redisLockClient;

    /***
     * 功能描述: 会出现超卖情况的减少库存方式
     * @author: dazhi
     * @date: 2021/2/3
     */
    public void secKill(Long goodsId, Long memberId) {

        try {
           // Boolean aBoolean = redisLockClient.tryLock(SecKillConstant.secKillRedisKey + goodsId, LockType.FAIR, 1000L, 3000L,TimeUnit.MICROSECONDS);
            Boolean aBoolean =true;

            if(aBoolean){
                int stock = Integer.valueOf(redisTemplate.opsForValue().get(SecKillConstant.secKillRedisKey + goodsId).toString());
                log.info("下单前的库存：{}",stock);
                if (stock <= 0) {
                    log.info("库存不足");
                    return;
                }
                redisTemplate.opsForValue().set(SecKillConstant.secKillRedisKey + goodsId, stock - 1);
                redisLockClient.unLock(SecKillConstant.secKillRedisKey + goodsId,LockType.FAIR);
                orderMasterService.orderGenerate(goodsId, memberId);

            }
        } catch (Exception e) {
            log.info("服务异常，稍后再试");
        }

    }
}
